//
//  YZMLockViewController.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/4/20.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMLockViewController.h"
#import "YZMLockIndicatorView.h"
#import "YZMLockPassword.h"
#import "YZMAlertView.h"

static const NSInteger lock_view_control_retry_time = 5;

@interface YZMLockViewController()<UITextFieldDelegate, YZMLockViewDelegate>

@property (nonatomic, strong) YZMLockIndicatorView* indicatorView; // 九点指示图
@property (nonatomic, strong) YZMLockView* lockview; // 触摸田字控件
@property (weak, nonatomic) UIImageView *preSnapImageView; // 上一界面截图
@property (weak, nonatomic) UIImageView *currentSnapImageView; // 当前界面截图

@property (strong, nonatomic) UILabel *tipLable;
@property (strong, nonatomic) UIButton *resetButton; // 重设/(取消)的提示按钮

@property (nonatomic, strong) NSString* savedPassword; // 本地存储的密码
@property (nonatomic, strong) NSString* passwordOld; // 旧密码
@property (nonatomic, strong) NSString* passwordNew; // 新密码
@property (nonatomic, strong) NSString* passwordConfirm; // 确认密码
@property (nonatomic, strong) NSString *tip1;
@property (nonatomic, strong) NSString *tip2;
@property (nonatomic, strong) NSString *tip3;

@end

@implementation YZMLockViewController{
    
    UIColor  *_normalColor;
    UIColor *_errorColor;
    NSInteger _currentStep;
    int _nRetryTimesRemain; // 剩余几次输入机会
    
    UIView *_passwordView;
    UITextField *_passwordTF;
}

- (id)init{
    
    self = [super init];
    if (self) {
        
        
    }
    return self;
}

- (void)setNLockViewType:(YZM_LOCK_TYPE)nLockViewType{
    
    _nLockViewType = nLockViewType;
    
    switch (_nLockViewType) {
        case YZM_LOCK_TYPE_FOR_CHECK:
            self.title = @"";
            self.tip1 = @"";
            break;
        case YZM_LOCK_TYPE_FOR_CREATE:
            self.title = @"设置手势密码";
            self.tip1 = @"请绘制解锁图案";
            self.tip2 = @"请重复绘制解锁图案";
            break;
        case YZM_LOCK_TYPE_FOR_MODIFY:
            self.title = @"修改手势密码";
            self.tip1 = @"请输入原手势密码";
            self.tip2 = @"请绘制解锁图案";
            self.tip3 = @"请重复绘制解锁图案";
            break;
        case YZM_LOCK_TYPE_FOR_CLEAN:
            self.title = @"关闭手势密码";
            self.tip1 = @"请输入原手势密码";
        default:
            break;
    }
}

- (id)initWithType:(YZM_LOCK_TYPE)type
{
    self = [self init];
    if (self) {
        
        self.nLockViewType = type;
    }
    return self;
}

- (void)viewDidLoad{
    
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:NO];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    _normalColor = [YZMAppStyle colorForYellowButton];
    _errorColor = [YZMAppStyle colorForRiseText];
    
    _nRetryTimesRemain = lock_view_control_retry_time;
    
    [self createObjects];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
#ifdef LLLockAnimationOn
    [self capturePreSnap];
#endif
    
    [super viewWillAppear:animated];
    
    if (_nLockViewType == YZM_LOCK_TYPE_FOR_CHECK) {
        
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
    
    _currentStep = 0;
    [self.tipLable setText:self.tip1];
    [self updateTipButtonStatus];
    
    // 尝试机会
    _nRetryTimesRemain = lock_view_control_retry_time;
    
    self.passwordOld = @"";
    self.passwordNew = @"";
    self.passwordConfirm = @"";
    
    // 本地保存的手势密码
    self.savedPassword = [YZMLockPassword loadLockPassword];
    [self updateTipButtonStatus];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)dismissSelf{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(YZMLockViewDidSuccessOpen:)]) {
        
        [self.delegate YZMLockViewDidSuccessOpen:self];
    }
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    [[YZMControllerManager sharedManager] dismissViewController];
}

- (void)backToHomePageForExitUser{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(YZMLockViewDidFailureOpen:)]) {
        
        [self.delegate YZMLockViewDidFailureOpen:self];
    }
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    [[YZMControllerManager sharedManager] dismissViewController];
}

#pragma mark 抖动动画
- (void)shakeAnimationForView:(UIView *)view
{
    CALayer *viewLayer = view.layer;
    CGPoint position = viewLayer.position;
    CGPoint left = CGPointMake(position.x - 6, position.y);
    CGPoint right = CGPointMake(position.x + 6, position.y);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [animation setFromValue:[NSValue valueWithCGPoint:left]];
    [animation setToValue:[NSValue valueWithCGPoint:right]];
    [animation setAutoreverses:YES]; // 平滑结束
    [animation setDuration:0.08];
    [animation setRepeatCount:2];
    
    [viewLayer addAnimation:animation forKey:nil];
}

- (void)setErrorTip:(NSString*)tip errorPswd:(NSString*)string
{
    // 直接_变量的坏处是
    [_tipLable setText:tip];
    [_tipLable setTextColor:_errorColor];
    //    [self shakeAnimationForView:_tipLable];
}

#pragma mark - 点击了按钮
- (void)tipButtonPressed:(UIButton *)sender{
    
    
    if (_nLockViewType == YZM_LOCK_TYPE_FOR_CREATE) {
        
        _currentStep = 0;
        self.passwordNew = @"";
        self.passwordConfirm = @"";
        
        [self setTip:self.tip1 animation:NO];
        [self updateTipButtonStatus];
    }else{
        
        _currentStep = 1;
        self.passwordNew = @"";
        self.passwordConfirm = @"";
        
        [self setTip:self.tip2 animation:NO];
        [self updateTipButtonStatus];
    }
    
}

#pragma mark - 显示提示
- (void)setTip:(NSString*)tip animation:(BOOL)animation
{
    [_tipLable setText:tip];
    [_tipLable setTextColor:_normalColor];
    
    if (animation) {
        
        _tipLable.alpha = 0;
        [UIView animateWithDuration:0.4
                         animations:^{
                             _tipLable.alpha = 1;
                         }completion:^(BOOL finished){
                         }
         ];
    }
}

- (void)refreshRecommandLabel:(NSString *)errorLockString{
    
    _nRetryTimesRemain--;
    
    if (_nRetryTimesRemain > 0) {
        
        [self setErrorTip:[NSString stringWithFormat:@"密码错误，您还可以输入%d次", _nRetryTimesRemain]
                errorPswd:errorLockString];
        
    } else {
        
        // 强制注销该账户，并清除手势密码，以便重设
        [YZMLockPassword saveLockPassword:nil];
        [[YZMUserService sharedService] logout];
        
        YZMAlertView *alertView = [YZMAlertView new];
        alertView.titleLabel.text = @"手势密码已失效";
        alertView.contentLabel.text = @"您已连续5次错误，手势密码已失效，需要重新登录。";
        [alertView.sureButton setTitle:@"重新登录" forState:UIControlStateNormal];
        alertView.cancelButton.hidden = YES;
        __weak YZMAlertView *_alertView = alertView;
        alertView.confirmHandle = ^() {
            
            [_alertView dismissWithAnimationFlag:NO];
            if (_nLockViewType == YZM_LOCK_TYPE_FOR_CHECK) {
                
                [YZMHCMInstance pushViewControllerWithName:@"login" andParams:@{YZDismissFlag:@(YES)}];
            } else {
                
                [YZMHCMInstance pushAfterRootWithName:@"login" andParams:nil atIndex:self.tabBarController.selectedIndex];
            }
            
            
            return YES;
        };
        //alertView.tag = TAG_FOR_ERROR_PASSWORD_ALERT_VIEW;
        [alertView showInView:self.navigationController.view];
    }
}

#pragma mark 新建/修改后保存
- (void)updateTipButtonStatus
{
    
    if (self.indicatorView) {
        
        [self.indicatorView setHidden:NO];
        
        // 更新指示圆点
        if (![self.passwordNew isEqualToString:@""] && (!self.passwordConfirm || self.passwordConfirm.length == 0)){
            
            
            [self.indicatorView setPasswordString:self.passwordNew];
            
        } else {
            
            [self.indicatorView setPasswordString:nil];
        }
    }
    
    switch (_nLockViewType) {
        case YZM_LOCK_TYPE_FOR_CREATE:{
            
            if (_currentStep == 0) {
                
                [self.resetButton setHidden:YES];
            }else{
                
                [self.resetButton setHidden:NO];
            }
        }
            break;
        case YZM_LOCK_TYPE_FOR_MODIFY:{
            
            if (_currentStep != 2) {
                
                [self.resetButton setHidden:YES];
            }else{
                
                [self.resetButton setHidden:NO];
            }
            
            if (_currentStep == 0) {
                
                [self.indicatorView setHidden:YES];
            }
        }
            break;
        default:
            break;
    }
}


#pragma mark - YZSLockViewDelegate

- (void)createLockString:(NSString *)string{
    
    if (!string || string.length == 0) {
        
        return;
    }
    
    _currentStep ++;
    
    switch (_nLockViewType) {
            
        case YZM_LOCK_TYPE_FOR_CHECK:{
            
            if ([string isEqualToString:self.savedPassword]){
                
                [self dismissSelf];
                
            }else{
                
                [self refreshRecommandLabel:string];
            }
        }
            break;
        case YZM_LOCK_TYPE_FOR_CREATE:{
            
            if (_currentStep == 1) {
                
                if (string.length < 4) {
                    
                    [self setErrorTip:@"至少链接4个点，请重试" errorPswd:string];
                    _currentStep = 0;
                    return;
                }
                
                /*保存第一次的数据*/
                self.passwordNew = string;
                self.passwordConfirm = nil;
                [self setTip:self.tip2 animation:YES];
                [self updateTipButtonStatus];
                
            }else{
                
                /*比较第一次和第二次的数据*/
                if ([self.passwordNew isEqualToString:string]) {
                    
                    [YZMLockPassword saveLockPassword:string];
                    [MBProgressHUD showMessage:@"手势密码创建成功"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:YZMUserDetailUpdateNotification object:self];
                    [[YZMControllerManager sharedManager] popViewController:nil animated:YES];
                    
                }else{
                    
                    _currentStep = 2;
                    [self setErrorTip:@"与上次输入不一致，请重试" errorPswd:string];
                }
            }
            
        }
            break;
        case YZM_LOCK_TYPE_FOR_MODIFY:{
            
            if (_currentStep == 1) {
                
                /*与旧密码比较*/
                if ([self.savedPassword isEqualToString:string]) {
                    
                    [self setTip:self.tip2 animation:YES];
                    [self.indicatorView setHidden:NO];
                    
                }else{
                    _currentStep = 0;
                    //[self setErrorTip:@"原手势密码错误" errorPswd:string];
                    [self refreshRecommandLabel:string];
                    break;
                }
            }else if (_currentStep == 2){
                
                if (string.length < 4) {
                    
                    [self setErrorTip:@"至少链接4个点，请重试" errorPswd:string];
                    _currentStep = 1;
                    return;
                }
                
                /*保存第一次的密码*/
                self.passwordNew = string;
                [self setTip:self.tip3 animation:YES];
                [self updateTipButtonStatus];
                
            }else{
                
                /*比较第一次和第二次的数据*/
                if ([self.passwordNew isEqualToString:string]) {
                    
                    [YZMLockPassword saveLockPassword:string];
                    [MBProgressHUD showMessage:@"手势密码修改成功"];
                    [[YZMControllerManager sharedManager] popViewController:nil animated:YES];
                    
                }else{
                    
                    _currentStep = 2;
                    [self setErrorTip:@"与上次输入不一致，请重试" errorPswd:string];
                }
            }
        }
            break;
        case YZM_LOCK_TYPE_FOR_CLEAN:{
            
            if ([string isEqualToString:self.savedPassword]){
                
                [YZMLockPassword saveLockPassword:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:YZMUserDetailUpdateNotification object:self];
                [[YZMControllerManager sharedManager] popViewController:nil animated:YES];
                
            }else{
                
                [self refreshRecommandLabel:string];
            }
        }
        default:
            break;
    }
}

- (void)showCheckUserAlertView{
    
    YZMAlertView *alertView = [YZMAlertView new];
    __weak YZMAlertView *_alertView = alertView;
    alertView.confirmHandle = ^(){
        NSString *password = _passwordTF.text;
        if (!password || password.length == 0) {
            
            [MBProgressHUD showMessage:@"请先输入密码"];
            return NO;
        }
        
        if (![[YZMUserService sharedService] checkPassword:password]) {
            
            [MBProgressHUD showMessage:@"密码错误"];
            return NO;
        }
        
        [self resignFirstResponderAll];
        [_alertView dismissWithAnimationFlag:NO];
        [self loginWithPassword:password];
        return YES;
    };
    alertView.titleLabel.text = @"忘记手势密码";
    //alertView.tag = TAG_FOR_INPUT_PASSWORD_ALERT_VIEW;
    alertView.contentLabel.text = [@"您的账号：" stringByAppendingString: [YZMUserService sharedService].user.detail.loginMobile];
    alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
    alertView.contentLabel.font = [YZMAppStyle mediumSizeFont];
    
    if (!_passwordView) {
        
        _passwordView = [UIView new];
        
        _passwordTF = [UITextField new];
        _passwordTF.layer.cornerRadius = 5.0;
        _passwordTF.layer.masksToBounds = YES;
        _passwordTF.layer.borderColor = [YZMAppStyle colorForGrayUnable].CGColor;
        _passwordTF.layer.borderWidth = 1;
        _passwordTF.placeholder = @"请输入登录密码";
        _passwordTF.textColor = [YZMAppStyle colorForGrayText];
        _passwordTF.font = [YZMAppStyle mediumSizeFont];
        _passwordTF.secureTextEntry = YES;
        [_passwordView addSubview:_passwordTF];
        [_passwordTF mas_makeConstraints:^(MASConstraintMaker *maker){
            
            maker.top.left.right.bottom.equalTo(_passwordView);
            maker.height.mas_equalTo(44);
        }];
        
        UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
        _passwordTF.leftView = blankView;
        _passwordTF.leftViewMode = UITextFieldViewModeAlways;
    }
    
    [_passwordTF setText:nil];
    _passwordTF.text = nil;
    _passwordTF.delegate = alertView;
    
    alertView.customView = _passwordView;
    [alertView show];
}

- (void)clickForExitAccount{
    
    YZMAlertView *alertView = [YZMAlertView new];
    alertView.titleLabel.text = @"退出登录";
    alertView.contentLabel.text = @"确定退出当前账号？";
    __weak YZMAlertView *_alertView = alertView;
    alertView.confirmHandle = ^(){
        [_alertView dismissWithAnimationFlag:NO];
        [[YZMUserService sharedService] logout];
        [self backToHomePageForExitUser];
        [self performSelector:@selector(dismissSelf) withObject:nil afterDelay:0.1];
        return YES;
    };
    [alertView showInView:self.view];
}

#pragma mark -- YZSAlertViewDelegate

- (void)loginSuccess{
    
    [self dismissSelf];
}


- (void)loginWithPassword:(NSString *)password{
    
    MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"登录中"];
    
    [[YZMUserService sharedService] loginWithUsername:[YZMUserService sharedService].historyUsername password:password success:^(YZMLoginResultModel *loginResultMode){
        
        [hud hide:NO];
        [self dismissSelf];
        [YZMLockPassword saveLockPassword:nil];
        
    }failure:^(NSError *error) {
        
        [hud hide:NO];
        [error yz_showMessage];
    }];
}

- (void)resignFirstResponderAll{
    
    [_passwordTF resignFirstResponder];
}

#pragma mark -- Private Method

- (void)createObjects{
    
    self.lockview = [YZMLockView new];
    self.lockview.delegate = self;
    [self.view addSubview:self.lockview];
    
    self.tipLable = [UILabel new];
    self.tipLable.font = [YZMAppStyle mediumSizeFont];
    self.tipLable.textColor = _normalColor;
    self.tipLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.tipLable];
    
    [self assignConstraints];
}

#define IPHONE_4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
#define UI_MARGIN_BOTTOM_FOR_LOCK_VIEW  (-160+ (IPHONE_4?90:0) + (iPhone5?40:0))

- (void)assignConstraints{
    
    /*手势密码图*/
    [self.lockview mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.bottom.equalTo(self.view).offset(UI_MARGIN_BOTTOM_FOR_LOCK_VIEW);
        maker.centerX.equalTo(self.view);
        maker.width.equalTo(self.view);
    }];
    
    /*手势密码图上方的提示语句*/
    [self.tipLable mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.centerX.equalTo(self.view);
        maker.bottom.equalTo(self.lockview.mas_top).offset(-15);
        maker.height.mas_equalTo(17);
    }];
    
    if (_nLockViewType == YZM_LOCK_TYPE_FOR_CHECK) {
        
        
        UILabel *nameLabel = [UILabel new];
        nameLabel.text = [YZMUserService sharedService].user.detail.loginMobile;
        nameLabel.textColor = _normalColor;
        nameLabel.font = [YZMAppStyle fontWithSize:15];
        [self.view addSubview:nameLabel];
        [nameLabel mas_makeConstraints:^(MASConstraintMaker *maker){
            
            maker.bottom.equalTo(self.tipLable.mas_top).offset(-10);
            maker.centerX.equalTo(self.view);
        }];
        
        
        UIImageView *imageView = [UIImageView new];
        imageView.image = [UIImage imageNamed:@"avatar"];
        [self.view addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *maker){
            
            maker.width.height.mas_equalTo(50);
            maker.centerX.equalTo(self.view);
            maker.bottom.equalTo(nameLabel.mas_top).offset(-10);
        }];
        
        
        UIButton *forgotButton = [UIButton new];
        [forgotButton setTitle:@"忘记手势密码" forState:UIControlStateNormal];
        [forgotButton setTitleColor:_normalColor forState:UIControlStateNormal];
        [forgotButton.titleLabel setFont:[YZMAppStyle mediumSizeFont]];
        forgotButton.titleEdgeInsets = UIEdgeInsetsMake(4, 0, 4, 0);
        [forgotButton addTarget:self action:@selector(showCheckUserAlertView) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:forgotButton];
        [forgotButton mas_makeConstraints:^(MASConstraintMaker *maker){
            
            maker.left.equalTo(self.view).offset(30);
            maker.bottom.equalTo(self.view).offset(-24);
        }];
        
        UIButton *exitButton = [UIButton new];
        [exitButton setTitle:@"退出登录" forState:UIControlStateNormal];
        [exitButton setTitleColor:_normalColor forState:UIControlStateNormal];
        [exitButton.titleLabel setFont:[YZMAppStyle mediumSizeFont]];
        exitButton.titleEdgeInsets = UIEdgeInsetsMake(4, 0, 4, 0);
        [exitButton addTarget:self action:@selector(clickForExitAccount) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:exitButton];
        [exitButton mas_makeConstraints:^(MASConstraintMaker *maker){
            
            maker.right.equalTo(self.view).offset(-30);
            maker.bottom.equalTo(self.view).offset(-24);
        }];
        
    }else if (_nLockViewType == YZM_LOCK_TYPE_FOR_CREATE || _nLockViewType == YZM_LOCK_TYPE_FOR_MODIFY) {
        
        self.indicatorView = [YZMLockIndicatorView new];
        [self.view addSubview:self.indicatorView];
        [self.indicatorView mas_makeConstraints:^(MASConstraintMaker *maker){
            
            maker.centerX.equalTo(self.view);
            maker.bottom.equalTo(self.lockview.mas_top).offset(-50);
        }];
        
        self.resetButton = [UIButton new];
        self.resetButton.hidden = YES;
        [self.resetButton setTitle:@"重新设置" forState:UIControlStateNormal];
        [self.resetButton setTitleColor:_normalColor forState:UIControlStateNormal];
        [self.resetButton.titleLabel setFont:[YZMAppStyle mediumSizeFont]];
        self.resetButton.titleEdgeInsets = UIEdgeInsetsMake(4, 0, 4, 0);
        [self.resetButton addTarget:self action:@selector(tipButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.resetButton];
        [self.resetButton mas_makeConstraints:^(MASConstraintMaker *maker){
            
            maker.centerX.equalTo(self.view);
            maker.top.equalTo(self.lockview.mas_bottom).offset(PAGECONTENTMARGIN);
        }];
    }
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMLockViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (void)updateWithParams:(NSDictionary *)params{
    
    self.nLockViewType = [params[@"type"] integerValue];
}

@end
